package com.areaCalc;

import java.util.ArrayList;
import java.util.List;

import util.Calculator;
import util.Point;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class CalculateArea extends MapActivity {
	private LocationManager locMgr;
	private Button start;
	private Button stop;
	private Button calculate;
	private List<Point> points;
	private Calculator calculator;
	private MapView mapView;
	private MapController controller;
	private List<Overlay> mapOverlays;
	private List<GeoPoint> geoPoints;
	private Double area;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.calculate_area_activity);
		calculator = new Calculator();
		points = new ArrayList<Point>();
		geoPoints = new ArrayList<GeoPoint>();
		start = (Button)findViewById(R.id.start_area_calculator);
		stop = (Button)findViewById(R.id.stop_area_calculator);
		calculate = (Button) findViewById(R.id.calculate_area_activity_button);
		mapView = (MapView) findViewById(R.id.mapView);
		mapView.setBuiltInZoomControls(true);
		start.setOnClickListener(onStart);
		stop.setOnClickListener(onStop);
		calculate.setOnClickListener(onCalculate);
	}

	View.OnClickListener onStart = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			controller = mapView.getController();
			locMgr=(LocationManager)getSystemService(LOCATION_SERVICE);
			locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
					0, 0.5f,onLocationChange);
			controller.animateTo(findInicialPoint());
			controller.setZoom(17);
			mapView.invalidate();

			start.setVisibility(View.INVISIBLE);
			stop.setVisibility(View.VISIBLE);
		}

	};

	View.OnClickListener onStop = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			mapOverlays = mapView.getOverlays(); 
			mapOverlays.add(new MyOverlay(mapView, geoPoints, true));
			mapView.invalidate();
			locMgr.removeUpdates(onLocationChange);
			stop.setVisibility(View.INVISIBLE);
			start.setVisibility(View.VISIBLE);
		}
	};

	View.OnClickListener onCalculate = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			try {
				area = calculator.calculateArea(points);
				toast("The area calculate is: " +area.toString());
			} catch (Exception e) {
				toast("Failed to calculate area");
			}

		}
	};

	public void toast(String message) {
		Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
		toast.show();

	}
	private LocationListener onLocationChange=new LocationListener() {
		public void onLocationChanged(Location location) {
			insertLocation();
		}
		public void onProviderDisabled(String provider) {
			// required for interface, not used
		}
		public void onProviderEnabled(String provider) {
			// required for interface, not used
		}
		public void onStatusChanged(String provider, int status,
				Bundle extras) {
			// required for interface, not used
		}
	};

	private void insertLocation() {
		Location loc=locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (loc==null) {
			Toast.makeText(this, "No location available", Toast.LENGTH_SHORT).show();
		}else {
			try {
				double lat = loc.getLatitude();
				double lon = loc.getLongitude();
				GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lon* 1E6));
				geoPoints.add(point);
				points.add(calculator.convertToMeters(lat, lon));
			} catch (Exception e) {
				Toast.makeText(this, "Could not convert this", Toast.LENGTH_SHORT);
			}
		}
	}

	private GeoPoint findInicialPoint() {
		Location loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (loc==null) {
			Toast.makeText(this, "No location available", Toast.LENGTH_SHORT).show();
		}else {
			double lat = loc.getLatitude();
			double lon = loc.getLongitude();
			GeoPoint initialPoint = new GeoPoint((int) (lat * 1E6), (int) (lon* 1E6));
			geoPoints.add(initialPoint);
			return initialPoint;
		}
		return new GeoPoint(0,0);
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(this).inflate(R.menu.save, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId()==R.id.save_menu) {
			Intent saveAct = new Intent(CalculateArea.this, SaveActivity.class);
			if(area != null) {
				saveAct.putExtra("Value", area);
			}else {
				saveAct.putExtra("Value", 0.0);
			}
			saveAct.putExtra("isArea", true);
			startActivity(saveAct);
			return(true);
		}else if(item.getItemId() == R.id.list_menu_calcArea) {
			Intent listView = new Intent(CalculateArea.this,CalculationList.class);
			startActivity(listView);
		}else if(item.getItemId()== R.id.reset) {
			mapView.getOverlays().clear();
			points.clear();
			geoPoints.clear();
			area = 0.0;
			mapOverlays.clear();
			mapView.invalidate();
		}
		return super.onOptionsItemSelected(item);
	}

}